var app = getApp();
var util = require('../../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    movies: [],
    requestUrl: "",
    navigateTitle: "",
    totalCount: 0,
    isEmpty: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var category = options.category;
    this.setData({
      navigateTitle: category
    })
    var baseUrl = '';
    switch (category) {
      case "正在上映的电影-上海": baseUrl = app.globalData.g_bageUrl +
        "/v2/movie/in_theaters";
        break;
      case "即将上映的电影": baseUrl = app.globalData.g_bageUrl +
        "/v2/movie/coming_soon";
        break;
      case "豆瓣电影Top250": baseUrl = app.globalData.g_bageUrl +
        "/v2/movie/top250";
        break;
    }
    // 设置当前请求的url
    this.setData({
      requestUrl: baseUrl
    });
    util.httpRequest(baseUrl, this.processDoubanData);
  },

  /**
   * 处理豆瓣传送过来的数据
   */
  processDoubanData(movieData) {
    var movies = [];
    for (var sub in movieData.subjects) {
      var ele = movieData.subjects[sub];
      var title = ele.title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + '...';
      }
      var temp = {
        stars: util.converStarsArr(ele.rating.stars),
        title: title,
        average: ele.rating.average,
        coverImagePath: ele.images.large,
        movieId: ele.id,
      }
      movies.push(temp);
    }

    var allMovies = [];
    // 如果没有数据，则补充新数据
    if(this.data.isEmpty) {
      allMovies = movies;
      this.setData({
        isEmpty: false
      })
    } else {
      // 如果有新数据，则把新老数据累加到一起
      allMovies = this.data.movies.concat(movies);
    }

    this.setData({
      totalCount: this.data.totalCount + 20,
      movies: allMovies
    });
    
    // 隐藏加载动画
    wx.hideNavigationBarLoading();
    wx.hideLoading();
    wx.stopPullDownRefresh();
  },

  /**
   * 点击进去详情页
   */
  onMovieTap(e) {
    var movieId = e.currentTarget.dataset.movieid;
    wx.navigateTo({
      url: '../movies-detail/movies-detail?movieId=' + movieId,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 在onReady里面页面渲染完成，才能动态的设置导航条title
    wx.setNavigationBarTitle({
      title: this.data.navigateTitle,
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      movies: [],
      totalCount: 0,
      isEmpty: true
    })
    var url = this.data.requestUrl + '?start=0&count=20';
    wx.showNavigationBarLoading();
    util.httpRequest(url, this.processDoubanData);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var url = this.data.requestUrl + '?start=' + this.data.totalCount + '&count=20';
    util.httpRequest(url, this.processDoubanData);
    wx.showLoading({
      title: '正在加载更多...',
      mask: true
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})